package cn.layou.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * netty服务端
 *
 * @author layou
 * @date 2021-04-24
 */
public class NettyServer {
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        EventLoopGroup workGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            ChannelFuture f = bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    clients.add(ctx.channel());
                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf buf = null;
                                    try {

                                        //打印接收到的消息
                                        buf = (ByteBuf) msg;
                                        byte[] bytes = new byte[buf.readableBytes()];
                                        buf.getBytes(buf.readerIndex(), bytes);
                                        String result = new String(bytes);
                                        System.out.println(result);

                                        //将该消息重写给全部客户端
                                        clients.writeAndFlush(buf);

                                    } finally {
                                        if(null != buf) {
                                            //如果申请的ByteBuf没有调用writeAndFlush()方法，需要手动释放申请的内存(netty 是直接操作内存，没有经过jvm，所以jvm不会垃圾回收这块内存)
                                           // ReferenceCountUtil.release(buf);
                                        }
                                    }
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();
                                    //删除保存的channel
                                    clients.remove(ctx.channel());
                                    ctx.close();
                                }
                            });
                        }
                    })
                    .bind(8888)
                    .sync();
            //维持channel阻塞
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
